package com.newpage.module_classin.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.stetho.common.LogUtil;
import com.newpage.module_classin.ConstantCommand;
import com.newpage.module_classin.R;
import com.newpage.module_classin.R2;
import com.newpage.module_classin.adapter.ChoiceQuestionAdapter;
import com.tstudy.blepenlib.BlePenStreamManager;
import com.tstudy.blepenlib.data.BleDevice;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.AppConfig;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.EventBus.bean.Answer_command;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BasePresenter;
import com.wetao.lib_common.base.BaseViewImp;
import com.wetao.lib_common.bean.ActionCommand;
import com.wetao.lib_common.bean.response.ClassAnswerInfo;
import com.wetao.lib_common.tsdBlePen.TsdPenUtil;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BitmapUtil;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MultiClickUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.zhangke.websocket.WebSocketHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import butterknife.BindView;
import cn.hzw.doodle.DoodleColor;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;

/**
 * author: zhouyh
 * created on: 4/6/21 2:52 PM
 * description: 答题互动界面
 */
@Route(path = ConstantArouter.PATH_CLASSIN_ANSWERACTIVITY)
public class AnswerActivity extends BaseActivity {


    private static final String TAG = "AnswerActivity";

    private final String RIGHT = "T";
    private final String WRONG = "F";

    //题型 1单选 2判断 3简答题 4 多选
    private final int TYPE_1 = 1;
    private final int TYPE_2 = 2;
    private final int TYPE_3 = 3;
    private final int TYPE_4 = 4;

    @Autowired
    String answerInfo;
    @Autowired
    String studentId;
    @Autowired
    String roomName;
    @Autowired
    String lessonName;
    @Autowired
    boolean mJoinRoom;  //直播间是否正常连接标志


    @BindView(R2.id.rv_choice_question)
    RecyclerView recyclerView;
    @BindView(R2.id.ll_judge_question)
    LinearLayout ll_judge_question;
    @BindView(R2.id.iv_answer_right)
    ImageView iv_answer_right;
    @BindView(R2.id.iv_answer_wrong)
    ImageView iv_answer_wrong;
    @BindView(R2.id.fl_doodle)
    FrameLayout fl_doodle;
    @BindView(R2.id.tv_submit)
    TextView tv_submit;


    private ChoiceQuestionAdapter optionAdapter;


    //答题互动答题数据
    private ClassAnswerInfo info;
    //学生答案列表
    private List<String> studentAnswer = new ArrayList<>();
    private int type = -1;
    private boolean isSingleChoice = true; //是否为单选题


    private Bitmap doodle_bitmap; //涂鸦bitmap
    private Bitmap small_bitmap;  //底图背景bitmap
    //保存作答图片地址
    private String picFilePath;
    private DoodleParams mDoodleParams;
    private IDoodle mDoodle;
    private DoodleView mDoodleView;
    private DoodleOnTouchGestureListener mTouchGestureListener;
    //当前PageID
    private String curPageAddress;

    //是否已经提交过
    private boolean isSubmit = false;
    //答题结果对错
    private Boolean answerResult = false;
    private boolean submit_style = false; //提交类型  false被动提交  true主动提交



    /**
     * 蓝牙笔
     */
    private boolean mIsSubmiting; //是否正在提交标志
    private CoordinateInfo mCurDot;//当前正在绘制的点；
    private ConcurrentLinkedQueue<CoordinateInfo> mOffLineDots = new ConcurrentLinkedQueue();
    private double m_scale = 1.41;//点阵纸宽高比  高:宽=1.41
    private float mTemp_x = 0f; //暂存转换后的坐标
    private float mTemp_y = 0f;
    private float m_tran_x = 0f; //轨迹移动的坐标
    private float m_tran_y = 0f; //轨迹移动的坐标
    private float m_tran_again_x = 0f; //题目移动后，再移动坐标
    private float m_tran_again_y = 0f; //题目移动后，再移动坐标
    private boolean mIsTran_x = false;  //是否允许滚动
    private boolean mIsTran_y = false;  //是否允许滚动
    private boolean isMove = false;  //是否画笔在移动
    private int mPic_w = 2149;  //固定点阵纸 宽
    private int mPic_h = 3023;  //固定点阵纸 高
    private int fl_width;  //界面宽
    private int fl_height; //界面高
    private int fl_cur_height;  //当前画布高度

    private boolean mIsPenAutoConnect = false; //判断蓝牙笔是否要自动连接
    private boolean mIsPenAutoConnecting = false;//判断已经搜索到蓝牙笔，正在自动连接


    private TsdService.OnDataReceiveListener tsdListener = new TsdService.OnDataReceiveListener() {
        @Override
        public void onErrTsdPen(int code, String msg) {
            if(mIsPenAutoConnect) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onRefreshScan(boolean isScaning) {
            if(mIsPenAutoConnect && !mIsPenAutoConnecting && !isScaning) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onAddDevice(BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
                if(bleDevice.getMac().equals(mac)) {
                    mIsPenAutoConnecting = true;
                    mTsdServiceBinder.on_penConnect(bleDevice);
                }
            }
        }

        @Override
        public void onPenConnectStatus(int code, BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                if (code == TsdService.CONN_PEN_SUCCESS) {
                    mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    DialogXUtil.waitDialogDismiss();
                    BlePenStreamManager.getInstance().setRealtimeMode();
                    DialogXUtil.customDialogShow("自动重连成功！", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                } else if (code == TsdService.CONN_PEN_FAIL || code == TsdService.CONN_PEN_DIS) {
                    mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    DialogXUtil.waitDialogDismiss();
                    showNoPenConnectDialog(true);
                }
            }
        }

        @Override
        public void onGetPenInfo(int batteryPercent, int memoryPercent, int memoryByteNum) {

        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onTeacherExitSmallTest() {

        }

        @Override
        public void onCoordDraw(CoordinateInfo coordinateInfo) {
            if (type != TYPE_3) {
                return;
            }
            if (mIsSubmiting) {
                return;
            }
            //只允许一张纸作答
            mCurDot = coordinateInfo;
            if (mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
                LogUtils.i("answerActivity" + ":pageAddress =" + curPageAddress);
                if (curPageAddress == null) {
                    curPageAddress = mCurDot.pageAddress;
                } else if (!mCurDot.pageAddress.equals(curPageAddress)) {
                    ToastUtil.initToast("请在同一页作答");
                    return;
                }
            }

            mOffLineDots.offer(coordinateInfo);

            nextDots();

        }

    };

    private void nextDots() {
        while (!mOffLineDots.isEmpty()) {
            mCurDot = mOffLineDots.poll();
            scrollBitmap();
            drawBitmap();
        }
    }


    private void scrollBitmap() {

        /**
         * 处理手势移动逻辑
         */
        if (m_tran_again_y > mDoodleView.getHeight() && fl_cur_height!= mDoodleView.getHeight()*2){
            fl_cur_height = mDoodleView.getHeight() * 2;
            mIsTran_y = true;
        }else if (m_tran_again_y > 0 && fl_cur_height!=mDoodleView.getHeight()){
            fl_cur_height = mDoodleView.getHeight();
            mIsTran_y = true;
        }
        float temp_y = TsdPenUtil.getRealX(mCurDot.coordY, mPic_h) * mDoodleView.getZoomerScale();
        LogUtils.i("m1: 滚动坐标到x=" + m_tran_x + ", y = " + temp_y +
                ", m_tran_x = " + 0 + ", m_tran_y = " + temp_y + "big_w=" + mDoodleView.getWidth() + "big_h=" + mDoodleView.getHeight());
        if (temp_y > (2 * mDoodleView.getHeight()) && fl_cur_height <= (2 * mDoodleView.getHeight())) {
            LogUtils.e("倍数：" + 3);
            fl_cur_height = mDoodleView.getHeight() * 3;
            mIsTran_y = true;
        } else if (temp_y > mDoodleView.getHeight() && temp_y < (2 * mDoodleView.getHeight())
                && fl_cur_height != (2 * mDoodleView.getHeight())) {
            LogUtils.e("倍数：" + 2);
            fl_cur_height = mDoodleView.getHeight() * 2;
            mIsTran_y = true;
        } else if (temp_y < mDoodleView.getHeight() && fl_cur_height > mDoodleView.getHeight()) {
            LogUtils.e("倍数：" + 1);
            fl_cur_height = mDoodleView.getHeight();
            mIsTran_y = true;
        }

        m_tran_again_x = 0;
        m_tran_again_y = 0;
        if (mIsTran_y && !isMove) {
            mIsTran_y = false;
            m_tran_y = fl_cur_height - mDoodleView.getHeight();
            mTouchGestureListener.setDoodleTranslationXY(0, -m_tran_y);
        }
    }

    /**
     * 绘制笔迹
     */
    private void drawBitmap() {
        mTemp_x = TsdPenUtil.getRealX(mCurDot.coordX, mPic_w) * mDoodleView.getZoomerScale();
        mTemp_y = TsdPenUtil.getRealY(mCurDot.coordY, mPic_h) * mDoodleView.getZoomerScale() - m_tran_y;
        LogUtils.i("m1: 绘制坐标：mTemp_x = " + mTemp_x + ", mTemp_y = " + mTemp_y);
        if (mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            isMove = false;
            mTouchGestureListener.r_onDown(mTemp_x, mTemp_y);
            mTouchGestureListener.r_onScrollBegin(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_COODINAT_MESSAGE) {
            isMove = true;
            mTouchGestureListener.r_onScroll(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_UP_MESSAGE) {
            isMove = false;
            mTouchGestureListener.r_onScrollEnd(mTemp_x, mTemp_y);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.classin_activity_answer;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public BaseViewImp createView() {
        return null;
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        initTitleLayout();
        initView();
        initData();


    }

    @Override
    public boolean getIsBindTsdService() {
        return true;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return tsdListener;
    }


    private void initData() {
        if (answerInfo != null) {
            info = ClassAnswerInfo.objectFromData(answerInfo);
            type = info.getQuestionType();
            setTvTitle(getTitle(info.getQuestionType()), true);
        }

        tips();


    }

    /**
     * 初始化选择题
     */
    private void initChoiceRcy() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(layoutManager);
        optionAdapter = new ChoiceQuestionAdapter(this, isSingleChoice);
        optionAdapter.setData(info.getOptions());
        optionAdapter.setOnItemClickListener(position -> {
            if (studentAnswer.contains(info.getOptions().get(position))) {
                studentAnswer.remove(info.getOptions().get(position));
            } else {
                if (isSingleChoice) studentAnswer.clear();
                studentAnswer.add(info.getOptions().get(position));
            }
        });

        recyclerView.setAdapter(optionAdapter);

    }


    private void tips() {
        ToastUtil.reset();
        switch (type) {
            case TYPE_3:
                setPicFilePath();
                initDoodleView();

                if (TsdService.M_BLE_DEVICE == null) {
                    showNoPenConnectDialog(false);
                    return;
                } else {
                    ToastUtil.initToast("请在作答本上进行作答");
                }
                break;
            case TYPE_1:
            case TYPE_4:
                ToastUtil.initToast("请在屏幕上进行作答");
                initChoiceRcy();
                break;
            case TYPE_2:
                ToastUtil.initToast("请在屏幕上进行作答");
                break;
        }
        showContentView();

    }

    private void initDoodleView() {
        fl_doodle.post(() -> {
            fl_width = fl_doodle.getMeasuredWidth();
            fl_height = fl_doodle.getMeasuredHeight();
            small_bitmap = BitmapUtil.ReadBitmapById_4444(this, R.drawable.common_caogaozhi_0);
            doodle_bitmap = resizeImage(small_bitmap, fl_width, (int) (fl_width * m_scale));
            fl_cur_height = fl_height;
            initDoodleData();
        });
    }

    /**
     * 提示未连接蓝牙笔
     */
    private void showNoPenConnectDialog(boolean isAgain) {
        String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
        if(StringUtil.isEmpty(mac) || isAgain) {
            DialogXUtil.customDialogShow(isAgain ? "自动重连失败！" : "智能笔连接未连接！\r\n请连接智能笔后再作答", "", "手动连接", true, new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {

                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        } else {
            DialogXUtil.customDialogShow("智能笔连接未连接！\r\n请连接智能笔后再作答", "刷新自动重连", "手动连接", new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {
                    //自动连接
                    mIsPenAutoConnect = true;
                    DialogXUtil.waitDialogShow("正在自动连接智能笔...");
                    mTsdServiceBinder.on_startScan();
                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        }
    }


    /**
     * 提示未作答
     */
    private void showNotAnswerDialog() {
        DialogXUtil.customDialogShow("您还未作答,请作答后再提交！", "知道了", true, new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {

            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }


    private void showContentView() {
        if (type == TYPE_3) {
            fl_doodle.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            ll_judge_question.setVisibility(View.GONE);
        } else if (type == TYPE_2) {
            fl_doodle.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            ll_judge_question.setVisibility(View.VISIBLE);
        } else {
            fl_doodle.setVisibility(View.GONE);
            ll_judge_question.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {

        iv_back.setOnClickListener(v -> {
            dialogue_back();
        });
        tv_submit.setOnClickListener(v -> {

            if (!ComUtil.isNetworkConnected() || !mJoinRoom){
                ToastUtil.initToast(getResources().getString(R.string.network_disconnect_error));
                return;
            }

            if (!MultiClickUtil.isFastClick() || isSubmit) {
                ToastUtil.initToast("请不要重复提交");
                return;
            }
            submit_style = true;
            if (type == TYPE_3 && TsdService.M_BLE_DEVICE == null){
                showNoPenConnectDialog(false);
                return;
            }
            if (isNotAnswered(type)) {
                showNotAnswerDialog();
            } else {
                iv_back.setEnabled(false);
                submitAnswer(type);
            }
        });

        iv_answer_right.setOnClickListener(v -> {
            if (iv_answer_wrong.isSelected()) {
                studentAnswer.clear();
                iv_answer_wrong.setSelected(false);
            }
            if (studentAnswer.contains(RIGHT)) {
                studentAnswer.remove(RIGHT);
                iv_answer_right.setSelected(false);
            } else {
                studentAnswer.add(RIGHT);
                iv_answer_right.setSelected(true);
            }

        });
        iv_answer_wrong.setOnClickListener(v -> {
            if (iv_answer_right.isSelected()) {
                studentAnswer.clear();
                iv_answer_right.setSelected(false);
            }
            if (studentAnswer.contains(WRONG)) {
                studentAnswer.remove(WRONG);
                iv_answer_wrong.setSelected(false);
            } else {
                studentAnswer.add(WRONG);
                iv_answer_wrong.setSelected(true);
            }
        });
    }

    /**
     * 创建保存文件路径
     */
    private void setPicFilePath() {

        //String dirPath = getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        dirPath = dirPath + File.separator + "class_doodle";
        File picDirF = new File(dirPath);
        if (!picDirF.exists()) {
            boolean mkdirs = picDirF.mkdirs();
            if (!mkdirs) {
                LogUtils.e("m1:创建失败picDir：" + dirPath);
            } else {
                LogUtils.i("m1:创建成功picDir");
            }
        }
        picFilePath = dirPath + File.separator + "1.png";
        LogUtils.i("m1: 图片存储的路径：" + picFilePath);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                dialogue_back();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 判断是否作答过
     */
    private boolean isNotAnswered(int type) {
        boolean isNotAnswered = false;
        if (type == TYPE_3) {
            if (submit_style && (mDoodle.getAllItem() == null || mDoodle.getAllItem().size() == 0)) {
                isNotAnswered = true;
            }
        } else {
            if (submit_style && studentAnswer.size() == 0) {
                isNotAnswered = true;
            }
        }
        return isNotAnswered;
    }

    /**
     * 提交答案
     *
     * @param type
     */
    private void submitAnswer(int type) {
        if (type == TYPE_3) {
            //主观题
            showSubmitDialog();
            mIsSubmiting = true;
            subjectAnswer();
        } else {
            //客观题
            objectAnswer();
        }
    }

    /**
     * 处理客观题
     * 单选多选判断题
     */
    private void objectAnswer() {
        sendCommand(ConstantCommand.COMMAND_STUDENT_ANSWER_QUESTION, studentAnswer);
        isSubmit = true;
        if (submit_style) {
            ToastUtil.initToast("提交成功,请等待答题结果");
        }
        finish();
    }


    /**
     * 发送指令
     *
     * @param action
     */
    private void sendCommand(String action, List<String> answer) {
        ActionCommand command = new ActionCommand();
        command.setInstructions(action);
        command.setId(studentId);
        command.setRoomId(roomName);
        command.setLessonQuestionId(info.getLessonQuestionId());
        command.setAnswerContent(answer);
        WebSocketHandler.getDefault().send(gson.toJson(command));
        Answer_command answer_command = new Answer_command();
        answer_command.setType(type);
        answer_command.setAnswers(answer);
        answer_command.setSubmit_style(submit_style);
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_SUBMITED, gson.toJson(answer_command)));

    }


    /**
     * 处理主观题
     */
    private void subjectAnswer() {
        if (mDoodle.getAllItem() != null && mDoodle.getAllItem().size() > 0) {
            mDoodle.save();
        } else {
            DialogXUtil.waitDialogDismiss();
            sendCommand(ConstantCommand.COMMAND_STUDENT_ANSWER_QUESTION, new ArrayList<>());
            finish();
        }
    }


    private String getTitle(int type) {
        String title = "答题互动";
        switch (type) {
            case TYPE_1:
                title = "单选题";
                isSingleChoice = true;
                break;
            case TYPE_2:
                title = "判断题";
                break;
            case TYPE_3:
                title = "简答题";
                break;
            case TYPE_4:
                title = "多选题";
                isSingleChoice = false;
                break;
        }

        return title;
    }


    public Bitmap resizeImage(Bitmap bitmap, int width, int height) {
        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();

        float scaleWidth = ((float) width) / bmpWidth;
        float scaleHeight = ((float) height) / bmpHeight;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }


    /**
     * 保存方法
     */
    public void saveBitmap(Bitmap bitmap, String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
            //return;
        }
        String type = "";
        if ("PNG".equals(filePath.substring(filePath.lastIndexOf(".") + 1).toUpperCase())) {
            type = ".png";
        } else {
            type = ".jpg";
        }

        try {
            FileOutputStream out = new FileOutputStream(f);
            if (".png".equals(type)) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            } else {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }

            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 初始化涂鸦
     */
    private void initDoodleData() {

        fl_doodle.removeAllViews();
        mDoodleParams = new DoodleParams();
        mDoodleParams.mImagePath = picFilePath;
        mDoodleParams.mSavePath = picFilePath;
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;

        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */
        mDoodle = mDoodleView = new DoodleViewWrapper(this.getApplicationContext(), doodle_bitmap, false, true, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtils.i("m1:-----doodle----onSaved");
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtils.i("m1:-----doodle----doodleViewWrapper主线程ID: " + thread1.getId());
                LogUtils.i("m1:-----doodle----doodleViewWrapper当前线程ID: " + thread2.getId());


                saveBitmap(bitmap, mDoodleParams.mSavePath);
                String uploadFile = "0&" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + roomName + "_" + System.currentTimeMillis() + ".png";
                UploadOss.getInstance().upload2OSS(uploadFile, mDoodleParams.mSavePath, ossUploadListener, null);
            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtils.i("-----doodle----onReady");
            }
        });

        mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {

            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {

            }

            @Override
            public void onCallScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                LogUtils.i("m1:滚动手指：distanceX: " + distanceX + ", distanceY:" + distanceY);
                if (!mIsTran_y && mOffLineDots.isEmpty()) {
                    m_tran_again_y = m_tran_again_y + distanceY;
                    LogUtils.i("m1:滚动手指 边界" + (fl_cur_height - mDoodleView.getHeight()));
                    if (m_tran_again_y > 2 * mDoodleView.getHeight()) {
                        m_tran_again_y = 2 * mDoodleView.getHeight();
                    } else if (m_tran_again_y < 0) {
                        m_tran_again_y = 0;
                    }
                    LogUtils.i("m1:滚动手指 滚动" +  m_tran_again_y);
                    mTouchGestureListener.setDoodleTranslationXY(0,  -m_tran_again_y);
                }
            }

        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };
        mTouchGestureListener.setSupportScale(false); //禁止放大缩小
        setSupportDoodle(false);
        setSupportTrans(true);

        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(this.getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);
        mDoodleView.setStartXy(true);
        mDoodleView.setColor(new DoodleColor(Color.BLACK));
        mDoodleView.setCanvasWhite(true);

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        fl_doodle.addView(mDoodleView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);
        mDoodle.setZoomerScale((float)fl_width/mPic_w);

    }

    /**
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态
     */
    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, boolean isMask, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, isMask, listener);
        }
    }

    private void setSupportDoodle(boolean isSupport) {
        if (mTouchGestureListener != null) {
            mTouchGestureListener.setSupportDoodle(isSupport);
        }
    }

    private void setSupportTrans(boolean isSupport) {
        if (mTouchGestureListener != null) {
            mTouchGestureListener.setSupportTrans(isSupport);
        }
    }


    /**
     * 上传图片回调
     */
    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
            Thread thread1 = getMainLooper().getThread();
            Thread thread2 = Thread.currentThread();
            LogUtils.i("-----doodle----OSSUploadListener主线程ID: " + thread1.getId());
            LogUtils.i("-----doodle----OSSUploadListener当前线程ID: " + thread2.getId());
            isOssSuccess(uploadFile);
            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            hideSubmitDialog();
            ToastUtil.initToast("提交失败，请重试");
            return null;
        }
    };

    /**
     * 上传成功处理
     *
     * @param uploadFile
     */
    private void isOssSuccess(String uploadFile) {
        studentAnswer.clear();
        studentAnswer.add(uploadFile);
        hideSubmitDialog();
        sendCommand(ConstantCommand.COMMAND_STUDENT_ANSWER_QUESTION, studentAnswer);
        finish();
        ToastUtil.initToast("答题提交成功");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void showSubmitDialog() {
        DialogXUtil.waitDialogShow("正在上传作答...");
    }

    public void hideSubmitDialog() {
        iv_back.setEnabled(true);
        DialogXUtil.waitDialogDismiss();
    }

    public void dialogue_back() {
        DialogXUtil.customDialogShow(getString(R.string.class_command_exit), new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_BACK_FINISH,null));
                finish();
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        releaseWakeLock();
    }

    @Override
    protected void onResume() {
        super.onResume();
        acquireWakeLock();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        int action = messageEvent.getAction();
        if (action == EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_ANSWER_EXIT) {
            LogUtil.i("command:" + "接收到退出答题指令");
            submit_style = false;
            iv_back.setEnabled(false);
            submitAnswer(type);
        } else if (action == EventBusMessage.EVENT_BUS_ACTION_NOT_EXIT_ANSWER) {
            LogUtils.i("enterAnswer: finish");
            finish();
        } else if (action == EventBusMessage.EVENT_BUS_ACTION_ROOM_CONNECT_STATE){
            String msg = messageEvent.getMsg();
            if ("false".equals(msg)){
                mJoinRoom = false;
            }else {
                mJoinRoom = true;
            }
        }
    }
}
